//
//  MultilevelMenu.m
//  MultilevelMenu
//
//  Created by gitBurning on 15/3/13.
//  Copyright (c) 2015年 BR. All rights reserved.
//

#import "MultilevelMenu.h"
#import "CollectionHeader.h"
#import "MultilevelTableViewCell.h"
#import "MultilevelCollectionViewCell.h"
#import "UIImageView+WebCache.h"
#import "Screen.h"
#import "INHeader.h"
#import "PKRequestManager.h"
#import "GiftModel.h"
#import "GiftSubcategoriesModel.h"
#import "GiftDetailCollectionViewController.h"
#import "FMDB.h"


#define kImageDefaultName @"tempShop"
#define kMultilevelCollectionViewCell @"MultilevelCollectionViewCell"
#define kMultilevelCollectionHeader   @"CollectionHeader"
#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]



@interface MultilevelMenu()

@property (strong, nonatomic) UITableView * leftTablew;
@property (strong, nonatomic) UICollectionView * rightCollection;

@property (assign, nonatomic) BOOL isReturnLastOffset;

@property (nonatomic, assign) BOOL isFirst; //用来取消左边tableView第一次被选中的cell的选中状态
@property (nonatomic, strong) FMDatabase *db;
@end



@implementation MultilevelMenu

-(id)initWithFrame:(CGRect)frame
{
    
    if (self == [super initWithFrame:frame]) {
        
        
        self.leftSelectColor = [UIColor redColor];
        self.leftSelectBgColor = [UIColor whiteColor];
        self.leftBgColor = UIColorFromRGB(0xF3F4F6);
        self.leftSeparatorColor = UIColorFromRGB(0xE5E5E5);
        self.leftUnSelectBgColor = UIColorFromRGB(0xF3F4F6);
        self.leftUnSelectColor = [UIColor blackColor];
        
        self.allData = [NSMutableArray arrayWithCapacity:0];
        
        /**
         左边的视图
         */
        self.leftTablew=[[UITableView alloc] initWithFrame:CGRectMake(0, 0, kLeftWidth, frame.size.height)];
        
        self.leftTablew.dataSource = self;
        self.leftTablew.delegate = self;
        
        self.leftTablew.backgroundColor = self.leftBgColor;
        self.leftTablew.separatorColor = self.leftSeparatorColor;
        self.leftTablew.showsVerticalScrollIndicator = NO;
        
        
        [self addSubview:self.leftTablew];
        
        
        if ([self.leftTablew respondsToSelector:@selector(setLayoutMargins:)]) {
            self.leftTablew.layoutMargins = UIEdgeInsetsZero;
        }
        if ([self.leftTablew respondsToSelector:@selector(setSeparatorInset:)]) {
            self.leftTablew.separatorInset = UIEdgeInsetsZero;
        }
        
        
        /**
         右边的视图
         */
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.minimumInteritemSpacing = 0.f;//左右间隔
        flowLayout.minimumLineSpacing = 0.f;
        float leftMargin = 0;
        self.rightCollection = [[UICollectionView alloc] initWithFrame:CGRectMake(kLeftWidth + leftMargin,0,SCREEN_WIDTH - kLeftWidth - leftMargin * 2,frame.size.height) collectionViewLayout:flowLayout];
        
        self.rightCollection.delegate = self;
        self.rightCollection.dataSource = self;
        
        UINib *nib = [UINib nibWithNibName:kMultilevelCollectionViewCell bundle:nil];
        [self.rightCollection registerNib: nib forCellWithReuseIdentifier:kMultilevelCollectionViewCell];
        
        UINib *header = [UINib nibWithNibName:kMultilevelCollectionHeader bundle:nil];
        [self.rightCollection registerNib:header forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:kMultilevelCollectionHeader];
        
        self.rightCollection.backgroundColor = self.leftSelectBgColor;
        self.backgroundColor = self.leftSelectBgColor;
        
        self.rightCollection.showsVerticalScrollIndicator = NO;
        
        
        
        self.isFirst = YES;
        self.isReturnLastOffset = YES;
        [self addSubview:self.rightCollection];
        _selectIndex = 0;
        
        _beforeIndex = 0;
        
        [self parsarData];
        
        //  创建数据库及表
        [self creatDataBase];
        [self searchFromData];
    }
    return self;
}




#pragma mark ---  解析数据
- (void)parsarData{
    
    [PKRequestManager manager:GET requestWith:KGiftSortURL parDic:nil finish:^(NSData *data) {
        if (data == nil) {
            return ;
        }
        [self deleteDataOfHeader];
        [self.allData removeAllObjects];
        NSDictionary *parDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves | NSJSONReadingMutableContainers error:nil];
        NSArray *arr = parDic[@"data"][@"categories"];
        for (NSDictionary *dic in arr) {
            GiftModel *model = [[GiftModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.allData addObject:model];
            [self insertDataOfHeader:model];
        }
        
        [self reloadData];
  
    } error:^(NSError *error) {
        
    }];
}



-(void)setNeedToScorllerIndex:(NSInteger)needToScorllerIndex{
    
    _needToScorllerIndex = needToScorllerIndex;
    
    if (needToScorllerIndex > 0) {
        
        MultilevelTableViewCell *cell = (MultilevelTableViewCell*)[self.leftTablew cellForRowAtIndexPath:[NSIndexPath indexPathForRow:needToScorllerIndex inSection:0]];
        UILabel *line = (UILabel*)[cell viewWithTag:100];
        line.backgroundColor = cell.backgroundColor;
        cell.titile.textColor = self.leftSelectColor;
        cell.backgroundColor = self.leftSelectBgColor;
        
        //  当界面刷新后,选中与左边选中的标题对应的cell
        [self.leftTablew selectRowAtIndexPath:[NSIndexPath indexPathForRow:_needToScorllerIndex inSection:0] animated:YES scrollPosition:UITableViewScrollPositionTop];
        [self.rightCollection scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:_needToScorllerIndex] atScrollPosition:UICollectionViewScrollPositionTop animated:YES];
        _selectIndex = needToScorllerIndex;
        
        [self.rightCollection reloadData];
    }
}



#pragma mark --- 给各种颜色设置重写set方法
-(void)setLeftBgColor:(UIColor *)leftBgColor{
    
    _leftBgColor = leftBgColor;
    self.leftTablew.backgroundColor = leftBgColor;
}

-(void)setLeftSelectBgColor:(UIColor *)leftSelectBgColor{
    
    _leftSelectBgColor = leftSelectBgColor;
    self.rightCollection.backgroundColor = leftSelectBgColor;
    self.backgroundColor = leftSelectBgColor;
}

- (void)setLeftSeparatorColor:(UIColor *)leftSeparatorColor{
    
    _leftSeparatorColor=leftSeparatorColor;
    self.leftTablew.separatorColor=leftSeparatorColor;
}



- (void)reloadData{
    
    [self.leftTablew reloadData];
    [self.rightCollection reloadData];
}




#pragma mark---左边的 tablew 代理

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.allData.count;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * Identifier=@"MultilevelTableViewCell";
    MultilevelTableViewCell * cell=[tableView dequeueReusableCellWithIdentifier:Identifier];
    
    if (!cell) {
        cell=[[NSBundle mainBundle] loadNibNamed:@"MultilevelTableViewCell" owner:self options:nil][0];
        
        UILabel * label=[[UILabel alloc] initWithFrame:CGRectMake(kLeftWidth - 0.5, 0, 0.5, 44)];
        label.backgroundColor = tableView.separatorColor;
        [cell addSubview:label];
        label.tag = 100;
    }

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    GiftModel *model = self.allData[indexPath.item];
    
    cell.titile.text = model.name;
    
    UILabel * line = (UILabel*)[cell viewWithTag:100];
    
    if (indexPath.row == self.selectIndex) {
        cell.titile.textColor = self.leftSelectColor;
        cell.backgroundColor = self.leftSelectBgColor;
        line.backgroundColor = cell.backgroundColor;
    } else {
        cell.titile.textColor = self.leftUnSelectColor;
        cell.backgroundColor = self.leftUnSelectBgColor;
        line.backgroundColor = tableView.separatorColor;
    }
    
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 44;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    MultilevelTableViewCell *cell = (MultilevelTableViewCell*)[tableView cellForRowAtIndexPath:indexPath];
    cell.titile.textColor = self.leftSelectColor;
    cell.backgroundColor = self.leftSelectBgColor;
    UILabel * line = (UILabel*)[cell viewWithTag:100];
    line.backgroundColor = cell.backgroundColor;
    
    _beforeIndex = indexPath.row;
    _selectIndex = indexPath.row;
    
    //  选中左边的lefttableview后,右边的collectionview被相应的选中
    [self.rightCollection scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:indexPath.row] atScrollPosition:UICollectionViewScrollPositionTop animated:YES];
    
    //  取消第一次的选中状态
    if (_isFirst) {
        MultilevelTableViewCell *cell = (MultilevelTableViewCell*)[tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:_needToScorllerIndex inSection:0 ]];
        [self tableView:self.leftTablew didDeselectRowAtIndexPath:[NSIndexPath indexPathForRow:_needToScorllerIndex inSection:0]];
        _isFirst = NO;
        cell.titile.textColor = self.leftUnSelectColor;
        UILabel *line = (UILabel*)[cell viewWithTag:100];
        line.backgroundColor = tableView.separatorColor;
        cell.backgroundColor = self.leftUnSelectBgColor;
    }
    
    self.isReturnLastOffset = NO;
    
    [self.rightCollection reloadData];
}


//  没被选中时改变各种设置的颜色
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    MultilevelTableViewCell *cell = (MultilevelTableViewCell*)[tableView cellForRowAtIndexPath:indexPath];
    
    cell.titile.textColor = self.leftUnSelectColor;
    UILabel *line = (UILabel*)[cell viewWithTag:100];
    line.backgroundColor = tableView.separatorColor;
    cell.backgroundColor = self.leftUnSelectBgColor;
}




#pragma mark---右边的 collectionView 代理

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    return _allData.count;
}



- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    GiftModel *model = _allData[section];
    return model.subcategories.count;
}



- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    
    GiftDetailCollectionViewController *giftDetailVC = [[GiftDetailCollectionViewController alloc] initWithCollectionViewLayout:flowLayout];
    GiftModel *model = self.allData[indexPath.section];
    
    NSNumber *iid = ((GiftSubcategoriesModel *)model.subcategories[indexPath.item]).subcategoriesId;
    NSInteger num = [iid integerValue];
    NSString *namestr = ((GiftSubcategoriesModel *)model.subcategories[indexPath.item]).name;
    
    giftDetailVC.nac = self.nac;
    giftDetailVC.nameString = namestr;
    giftDetailVC.urlString = [NSString stringWithFormat:kGiftDetailURL,(long)num];

    
    UITabBarController *tabBVC = (UITabBarController *)self.window.rootViewController;
    UINavigationController *navi = tabBVC.viewControllers[2];
    
    [navi pushViewController:giftDetailVC animated:YES];
}




- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    MultilevelCollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:kMultilevelCollectionViewCell forIndexPath:indexPath];
    
    GiftModel *model = self.allData[indexPath.section];
    cell.titile.text = ((GiftSubcategoriesModel *)model.subcategories[indexPath.item]).name;
    cell.backgroundColor = [UIColor clearColor];
    cell.imageView.backgroundColor = UIColorFromRGB(0xF8FCF8);
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:((GiftSubcategoriesModel *)model.subcategories[indexPath.item]).icon_url] ];
    
    return cell;
}



- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    
    CollectionHeader *view = nil;
    if ([kind isEqualToString: UICollectionElementKindSectionHeader]){
        
        view = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:kMultilevelCollectionHeader forIndexPath:indexPath];
        
//        view.bounds = CGRectMake(0, 0, SCREEN_WIDTH - 100, 56);
        GiftModel *model =  _allData[indexPath.section];
        view.headerTitile.text =[NSString stringWithFormat:@"──── %@ ────",model.name];
    }
    return view;
}



- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    return CGSizeMake(80, 100);
}


- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    
    return UIEdgeInsetsMake(0, 10, 0, 10);
}


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    
    CGSize size = {SCREEN_WIDTH,44};
    return size;
}



#pragma mark --- 记录滑动的坐标
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    
    if ([scrollView isEqual:self.rightCollection]) {
        
        self.isReturnLastOffset = YES;
    }
}



-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    if ([scrollView isEqual:self.rightCollection]) {
        
        [self tableView:self.leftTablew didDeselectRowAtIndexPath:[NSIndexPath indexPathForRow:_beforeIndex inSection:0]];
        NSArray *arr = self.rightCollection.visibleCells;
        NSIndexPath *indexPath = [self.rightCollection indexPathForCell:[arr firstObject]];
        
        
        _beforeIndex = indexPath.section;
        
        //  取消第一次的选中状态
        
        if (_isFirst) {
            [self tableView:self.leftTablew didDeselectRowAtIndexPath:[NSIndexPath indexPathForRow:_needToScorllerIndex inSection:0]];
            _isFirst = NO;
        }
        
        
        [self.leftTablew selectRowAtIndexPath:[NSIndexPath indexPathForRow:indexPath.section inSection:0] animated:YES scrollPosition:UITableViewScrollPositionTop];
        
        [self.leftTablew scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:indexPath.section inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
        
        MultilevelTableViewCell *cell = (MultilevelTableViewCell*)[self.leftTablew cellForRowAtIndexPath:[NSIndexPath indexPathForRow:indexPath.section inSection:0]];
        UILabel *line = (UILabel*)[cell viewWithTag:100];
        line.backgroundColor = cell.backgroundColor;
        cell.titile.textColor = self.leftSelectColor;
        cell.backgroundColor = self.leftSelectBgColor;
    }
}



-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if ([scrollView isEqual:self.rightCollection]) {

        [self tableView:self.leftTablew didDeselectRowAtIndexPath:[NSIndexPath indexPathForRow:_beforeIndex inSection:0]];
        NSArray *arr = self.rightCollection.visibleCells;
        NSIndexPath *indexPath = [self.rightCollection indexPathForCell:[arr firstObject]];


        _beforeIndex = indexPath.section;

        //  取消第一次的选中状态

        if (_isFirst) {
            [self tableView:self.leftTablew didDeselectRowAtIndexPath:[NSIndexPath indexPathForRow:_needToScorllerIndex inSection:0]];
            _isFirst = NO;
        }


        [self.leftTablew selectRowAtIndexPath:[NSIndexPath indexPathForRow:indexPath.section inSection:0] animated:YES scrollPosition:UITableViewScrollPositionTop];

        [self.leftTablew scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:indexPath.section inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];

        MultilevelTableViewCell *cell = (MultilevelTableViewCell*)[self.leftTablew cellForRowAtIndexPath:[NSIndexPath indexPathForRow:indexPath.section inSection:0]];
        UILabel *line = (UILabel*)[cell viewWithTag:100];
        line.backgroundColor = cell.backgroundColor;
        cell.titile.textColor = self.leftSelectColor;
        cell.backgroundColor = self.leftSelectBgColor;
    }
}




#pragma mark - 数据持久化
//  创建数据库
- (void)creatDataBase{
    
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]stringByAppendingPathComponent:@"Attack.db"];
    //        NSLog(@"%@",path);
    _db = [FMDatabase databaseWithPath:path];
    
    if (![_db open]) {
        NSLog(@"打开数据库失败");
    }
    
    [_db executeUpdate:@"CREATE TABLE IF NOT EXISTS AttackList (id integer PRIMARY KEY, titleName text, labelName text, icon_url text)"];
}



//  添加数据库
- (void)insertDataOfHeader:(GiftModel *)model{
    
    for (GiftSubcategoriesModel *giftModel in model.subcategories) {
        [_db executeUpdate:@"INSERT INTO AttackList (titleName, labelName, icon_url) VALUES (?,?,?)",model.name,giftModel.name,giftModel.icon_url];
    }
}



//  删除数据库
- (void)deleteDataOfHeader{
    
    [_db executeUpdate:@"DELETE FROM AttackList"];
}




//  查找数据库
- (void)searchFromData{
    
    FMResultSet *lists = [_db executeQuery:@"SELECT distinct titleName FROM AttackList"];
    while ([lists next]) {
        
        GiftModel *model = [[GiftModel alloc] init];
        model.name = [lists stringForColumn:@"titleName"];
        
        NSMutableArray *subArray = [NSMutableArray arrayWithCapacity:0];
        FMResultSet *lists2 = [_db executeQuery:@"SELECT labelName, icon_url FROM AttackList where titleName = ?",model.name];
        
        while ([lists2 next]) {
            GiftSubcategoriesModel *model1 = [[GiftSubcategoriesModel alloc] init];
            model1.icon_url = [lists2 stringForColumn:@"icon_url"];
            model1.name = [lists2 stringForColumn:@"labelName"];
            [subArray addObject:model1];
        }
        
        model.subcategories = subArray;
        
        [self.allData addObject:model];
    }
    [lists close];
    
}



@end






